package com.yc.favorite.servelt;

import com.google.gson.Gson;
import com.yc.favorite.bean.Tag;
import com.yc.favorite.mapper.TagMapper;
import com.yc.favorite.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/allTag.s")
public class AllTagServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

        // 改写法会自动关闭 session
        try(SqlSession session = MyBatisHelper.openSession()){
            TagMapper tagMapper = session.getMapper(TagMapper.class);
            List<Tag> tagList =  tagMapper.selectAll();
            // tagList ==> json
            String json = new Gson().toJson(tagList);
            resp.getWriter().append(json);
        }

    }
}
